<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form">
          <el-form-item>
            <el-checkbox v-model="isExpandAll" class="filter-item" border style="margin-right: 10px" @change="expandAll">
              <span v-if="isExpandAll">展开</span>
              <span v-else>收缩</span>
            </el-checkbox>
            <el-button class="filter-item" type="success" icon="el-icon-refresh-right" plain @click="refresh()">刷新</el-button>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button class="" type="primary" @click="add()">添加</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="tableRef" v-loading="loading" :data="datas" :max-height="height+60" style="width: 100%" row-key="id" border>
      <el-table-column prop="name" label="名称" min-width="180"/>
      <el-table-column prop="description" label="描述" min-width="240"/>
      <el-table-column prop="sorting" label="排序" min-width="75" align="center"/>
      <el-table-column prop="status" label="" min-width="75" align="center">
        <template slot="header">
          <span>是否显示</span>
        </template>
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="isActivate(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" min-width="160" align="center"/>
      <el-table-column label="操作" min-width="160" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加、修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" top="10vh" width="50%" :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="formRef" :rules="rules" :model="model" class="" label-width="100px">
        <el-form-item label="上一级" prop="parent_id">
          <el-cascader v-model="model.parent_id" :options="treeDatas" :props="props" placeholder="一级分类" style="width:100%" clearable filterable @change="pickParentId">
            <template slot-scope="{ node, data }">
              <span>{{ data.name }}</span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="model.name" placeholder="请输入名称" clearable/>
        </el-form-item>
        <el-form-item label="描述" prop="action">
          <el-input v-model="model.description" maxlength="100" placeholder="" clearable show-word-limit/>
        </el-form-item>
        <el-form-item label="排序" prop="sorting">
          <el-input-number v-model="model.sorting" :min="1" :max="99999" step-strictly controls-position="right"/>
        </el-form-item>
        <el-form-item v-if="model.id" label="创建时间" prop="created_at">
          <el-col :span="10">
            <el-input v-model="model.created_at" disabled/>
          </el-col>
          <el-col class="line" :span="4" style="text-align:center">更新时间</el-col>
          <el-col :span="10">
            <el-input v-model="model.updated_at" disabled/>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import {disabledTree} from '@/utils/index'
import {list, info, save, del, disable} from '@/api/admin/category'

export default {
  name: 'AdminArticlecate',
  directives: {},
  data() {
    return {
      name: '菜单',
      height: 680,
      loading: false,
      datas: [],
      dialogVisible: false,
      dialogTitle: '',
      btnLoading: false,
      model: {
        id: '',
        created_at: '',
        updated_at: '',
        parent_id: 0,
        name: '',
        description: '',
        sorting: 100,
        status: 1
      },
      rules: {
        name: [{required: true, message: '请输入名称', trigger: 'blur'}]
      },
      props: {checkStrictly: true, value: 'id', label: 'name'},
      isExpandAll: true,
      treeDatas: [],
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      list().then(res => {
        this.datas = res.data.data
        this.treeDatas = res.data.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 添加
    add(row) {
      this.dialogVisible = true
      this.dialogTitle = '新增'
      this.model = this.$options.data().model
      // object（对象）array（数组）这两个类型进行等于赋值的时候实际上是进行的引用，源数据改变后目标数据也就发生了变换
      //this.treeDatas = this.datas // 原始的的数据是一个数组或者对象，对于一个对象或者数组的时候他们等于是引用的地址是相同的，所以treeDatas改变时datas也会跟着改变
      this.treeDatas = JSON.parse(JSON.stringify(this.datas))
      if (row) {
        this.model.parent_id = row.id
      }
    },
    // 修改
    edit(row) {
      this.loading = true
      this.dialogVisible = true
      this.dialogTitle = '编辑：' + row.id
      this.treeDatas = disabledTree(JSON.parse(JSON.stringify(this.datas)), row.id)
      info({
        id: row.id
      }).then(res => {
        this.reset(res.data)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除ID： <span style="color:red">' + row.id + ' </span> 这条数据吗？',
        'ID：' + row.id,
        {type: 'warning', dangerouslyUseHTMLString: true}
      ).then(() => {
        this.loading = true
        del({
          id: row.id
        }).then(res => {
          this.loading = false
          if (res.statu == 1) {
            this.list()
            this.reset()
            this.$message.success(res.msg)
          } else {
            this.$message.info(res.msg)
          }
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 取消
    cancel() {
      this.reset()
      this.dialogVisible = false
    },
    // 提交
    submit() {
      this.$refs['formRef'].validate(valid => {
        if (valid) {
          this.btnLoading = true
          this.model.parent_id = this.getParentId(this.model.parent_id)
          save(this.model, 'post').then(res => {
            this.btnLoading = false
            this.list()
            this.dialogVisible = false
            this.$message.success(res.msg)
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      if (this.$refs['formRef'] !== undefined) {
        this.$refs['formRef'].resetFields()
      }
    },
    // 刷新
    refresh() {
      this.list()
    },

    // 展开/收起
    expandAll(e) {
      this.expandFor(this.datas, !e)
    },
    expandFor(data, isExpand) {
      data.forEach(i => {
        this.$refs.tableRef.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.expandFor(i.children, isExpand)
        }
      })
    },
    // 启用/禁用
    isActivate(row) {
      this.loading = true
      disable({
        id: row.id,
        status: row.status
      }).then(res => {
        this.list()
        this.$message.success(res.msg)
      }).catch(() => {
        this.list()
      })
    },
    // 父级选择
    pickParentId(value) {
      if (value) {
        //this.model.parent_id = this.getParentId(value)
      }
    },
    getParentId(ids) {
      if (Array.isArray(ids)) {
        // 取数组最后一项的值
        return ids[ids.length - 1]
      } else {
        return ids
      }
    }
  }
}
</script>
